<template>
  <div class="table-group">
    <div class="table-group__content">
      <c-table
        row-key="id"
        class="table-template__table"
        :loading="loading"
        :data="tableData"
        v-model:search="searchParams"
        v-model:paging="paging"
        @refresh="queryTableData"
      >
        <!-- 搜索栏 -->
        <template #search>
          <c-input v-model="searchParams._id" placeholder="请输入关键字" />
          <c-select
            v-if="userType == 1"
            width="100%"
            v-model="searchParams.image_type"
            prefixText="类型："
            :loading="typeLoading"
            :optionList="typeGroupData"
          ></c-select>
          <c-select v-model="searchParams.get_userid" prefixText="领取状态：">
            <el-option label="未领取" :value="-1"></el-option>
            <el-option label="已领取" :value="1"></el-option>
          </c-select>
        </template>

        <!-- 操作栏 -->
        <template #handle="{}">
          <el-button type="primary" @click="hanleModal">创建素材</el-button>
        </template>

        <!-- 表格 -->
        <template #table>
          <el-table-column label="ID" min-width="200" v-if="userType == 1">
            <template #default="{ row }">
              <div>ID：{{ row._id }}</div>
              <div>userid：{{ row.userid }}</div>
            </template>
          </el-table-column>
          <el-table-column label="标题" min-width="180">
            <template #default="{ row }">
              <div
                style="display: flex; align-items: center"
                v-if="row.title"
                @click="copyText(row.title)"
              >
                <span style="color: #000">标题：</span>{{ row.title }}
                <el-space wrap>
                  <el-icon style="margin-left: 10px" class="is-cursor-pointer">
                    <DocumentCopy />
                  </el-icon>
                  <el-icon @click.stop="toEditTitle(row)" size="16" class="is-cursor-pointer">
                    <Edit />
                  </el-icon>
                </el-space>
              </div>
              <el-button v-else type="primary" text @click="toEditTitle(row)">添加标题</el-button>

              <div
                style="display: flex; align-items: center"
                v-if="row.remark"
                @click="copyText(row.remark)"
              >
                <span style="color: #000">备注：</span>{{ row.remark }}
                <el-space wrap>
                  <el-icon style="margin-left: 10px" class="is-cursor-pointer">
                    <DocumentCopy />
                  </el-icon>
                  <el-icon @click.stop="toEditTitle(row)" size="16" class="is-cursor-pointer">
                    <Edit />
                  </el-icon>
                </el-space>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="内容" min-width="160">
            <template #default="{ row }">
              <div
                class="list-item-row"
                v-for="(contentItem, contentIndex) in row.content"
                :key="contentItem"
              >
                <span class="list-item-name">内容{{ contentIndex + 1 }}：</span>
                <span class="list-item-title">
                  【{{ getTypeGroupEnum?.[contentItem.image_type] }}，{{
                    contentItem.image_ids.length
                  }}张图，{{ contentItem.text_ids.length }}个文案】
                </span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间">
            <template #default="{ row }">
              {{ dayjs(row.create_time).format('YYYY-MM-DD HH:mm:ss') }}
            </template>
          </el-table-column>
          <el-table-column prop="get_userid" label="状态" v-if="userType == 1">
            <template #default="{ row }">
              <div>
                <span>显示状态：</span>
                <c-switch
                  v-model="row.status"
                  :activeValue="0"
                  :inactiveValue="1"
                  :before-change="() => switchBeforeChange(row)"
                  @refresh="queryTableData"
                ></c-switch>
              </div>
              <div v-if="row.get_userid == -1">未领取</div>
              <div v-else>
                <div>已领取</div>
                <div>{{ row.get_userid }}</div>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="240" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" text @click="handleDesc(row)">预览</el-button>
              <el-button type="primary" text @click="hanleGetCopy(row)">复制</el-button>
              <el-button type="danger" text @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </template>
      </c-table>
    </div>
  </div>

  <c-dialog title="预览素材" :width="600" name="material-preview-popup">
    <material-preview-popup></material-preview-popup>
  </c-dialog>

  <c-dialog
    title="复制素材"
    :close-on-click-modal="true"
    :width="globalStore.device.type == 'desktop' ? '1200' : '90%'"
    name="material-copy-popup"
  >
    <material-preview-popup isCopy isCover :isPreview="false"></material-preview-popup>
  </c-dialog>

  <c-dialog title="修改素材标题" :width="600" name="material-confirm-popup">
    <material-confirm-popup @refresh="queryTableData"></material-confirm-popup>
  </c-dialog>
</template>

<script setup name="el-encap.table-template">
import { ref, computed, onMounted } from 'vue';

// hooks
import { useTable } from '@/hooks/useTable/index.js';
import { useFetch } from '@/hooks/useFetch/index.js';

// components
import MaterialPreview from '@/components/material-preview/index.vue';
import { MessageBox } from '@/utils/message-box';
import { ElMessage } from 'element-plus';
import MaterialPreviewPopup from '@/components/material-preview-popup/index.vue';
import MaterialConfirmPopup from '@/components/material-confirm-popup/index.vue';

import { DocumentCopy, Edit } from '@element-plus/icons-vue';

// router
import { useRouter } from 'vue-router';
const router = useRouter();

// store modal
import { useModalStore } from '@/pinia/modules/modal';
const modalStore = useModalStore();

import { useGlobalStore } from '@/pinia/modules/global';
const globalStore = useGlobalStore();

// api
import { getApi } from '@/utils/tools';
import {
  pageMateralList,
  userPageMateralList,
  editeMateralStatus,
  getMateralV2,
  createGetMateralRecord,
} from '@/apis/material';
import { allTypeGroup, userListGroup } from '@/apis/user';

import { copyText } from '@/utils/tools.js';

// variable

import dayjs from 'dayjs';

const props = defineProps({
  // 0 普通用户 1 admin
  userType: {
    type: [String, Number],
    default: 0,
  },
});

const getTypeGroupEnum = computed(() => {
  return typeGroupData.value.reduce(function (obj, item) {
    obj[item.value] = item.label;
    return obj;
  }, {});
});

// 筛选列表
const { loading: statusLoading, data: statusData } = useFetch({
  api: getApi,
  params: { id: '123' },
});

// 分组列表
const { loading: groupLoading, data: groupData } = useFetch({
  api: getApi,
  params: { id: '123' },
});

// 分类列表
const { loading: typeLoading, data: typeGroupData } = useFetch({
  api: props.userType == 1 ? allTypeGroup : userListGroup,
});

// 表格相关
const { loading, paging, searchParams, tableData, queryTableData, delTableRow } = useTable({
  api: props.userType == 1 ? pageMateralList : userPageMateralList,
  params: {
    _id: '',
    image_type: '',
    get_userid: -1,
  },
  options: {},
  callBack: () => {},
});

// 时间筛选转换格式
const getCreateDate = computed({
  get() {
    const { startDate = '', endDate = '' } = searchParams.value;
    return [startDate, endDate];
  },
  set(value) {
    searchParams.value.startDate = value[0] || '';
    searchParams.value.endDate = value[1] || '';
    return;
  },
});

// 状态开关
const switchBeforeChange = async (row) => {
  return await editeMateralStatus({ _id: row._id, status: row.status == 1 ? 0 : 1 }).catch(
    (err) => err,
  );
};

// 详情页
const handleDesc = async (row) => {
  modalStore.openModal('material-preview-popup', { _id: row._id });
};

// 添加
const hanleModal = () => {
  if (props.userType == 1) {
    router.push({
      path: '/manage-center/materal-list/materal-create',
    });
  } else {
    router.push({
      path: '/user-manage/user-materal-list/user-materal-create',
    });
  }
};

const hanleGetMaterial = (item) => {
  MessageBox({
    title: '领取素材',
    message: '确定确定领取该素材？',
    beforeClose: async (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true;

        let res = await createGetMateralRecord({
          material_id: item._id,
        }).catch((err) => err);

        instance.confirmButtonLoading = false;

        if (res?.code !== 0) return;

        ElMessage.success('领取成功');
        // queryListGroup();
      }
      done();
    },
  });
};

// 编辑
const hanleModalEdit = () => {
  modalStore.openModal('popup', { type: 'add', data: [] });
};

const toEditTitle = (row) => {
  modalStore.openModal('material-confirm-popup', {
    _id: row._id,
    title: row.title,
    remark: row.remark,
  });
};

// 删除
const handleDelete = (row) => {
  delTableRow({
    api: editeMateralStatus,
    params: { _id: row._id, delete_status: 1 },
  });
};

const hanleGetCopy = (item) => {
  modalStore.openModal('material-copy-popup', { _id: item._id });
};

onMounted(() => {});
</script>

<style lang="scss" scoped>
.table-template {
  display: flex;
  flex-direction: column;
}

.table-group {
  height: 100%;
  display: flex;

  &__content {
    width: 100%;
    overflow: hidden;
    padding: 20px;
    box-sizing: border-box;
    @include card-box;
  }
}

.table-drag-img {
  font-size: 20px;
  vertical-align: middle;
  cursor: grab;
  margin: 0;
  padding: 0;
}

.list-item-row {
  padding: 4px 0;
}

.list-item-name {
  font-size: 14px;
}

.list-item-title {
  font-size: 14px;
  color: #333;
  // white-space: pre-wrap;
}

.preview {
  width: 375px;
  height: 100%;
  // overflow-y: auto;
  margin-left: 14px;
  @include card-box;
  flex-shrink: 0;
}
</style>
